import path from "path";
import fs from "fs";


const Reg = /\/\/fuck code begin([\w\W]+?)\/\/fuck code end/g

export function walk(dir, codeGenerator) {
    let files = fs.readdirSync(dir);
    for (let fileOrDirName of files) {

        const itemPath = path.join(dir, fileOrDirName);

        if (fs.statSync(itemPath).isDirectory()) {
            walk(itemPath, codeGenerator);
            continue;
        }
        if (path.extname(itemPath) != ".ts") {
            continue
        }
        console.log(itemPath);
        handleFile(itemPath, codeGenerator)
    }
}

export function handleFileContent(content, code) {
    return content.replaceAll(Reg, `//fuck code begin
${code}
//fuck code end`);
}

export function handleFile(filePath, codeGenerator) {
    let content = fs.readFileSync(filePath, {
        encoding: 'utf-8'
    })

    const newContent = handleFileContent(content, codeGenerator())
    fs.writeFileSync(filePath, newContent)

    // reg.exec(content)
    // console.log(content.match(reg))
    // console.log(content);
}